package com.asiainfo.ncrm.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;


import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

/**
 * @author:王剑洪
 * @date：2016年2月19日 @TODO: 文件操作工具类
 */
public class FileUtil {

	public static final String LOCAL_PATH = Environment.getExternalStorageDirectory().getPath();

	/**
	 * 写入log文件，不可续写
	 * 
	 * @param path
	 * @param content
	 * @return
	 */
	public static boolean writeLog(String path, String content) {
		if (!path.endsWith(".txt") && !path.endsWith(".log")) {
			path += ".txt";
		}
		File file = new File(path);
		OutputStream outstream = null;
		OutputStreamWriter out = null;
		try {
			outstream = new FileOutputStream(file);
			out = new OutputStreamWriter(outstream);
			out.write(content);
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * 写入log文件，可续写
	 * 
	 * @param fileName
	 * @param content
	 * @return
	 */
	public static boolean writeTxT(String fileName, String content) {
		fileName += ".txt";
		try {
			File file = File.createTempFile("tmp", null);
			file.deleteOnExit();
			RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
			FileInputStream fileInputStream = new FileInputStream(file);
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			raf.seek(raf.length());
			byte[] buff = new byte[64];
			int hasRead = 0;
			while ((hasRead = raf.read(buff)) > 0) {
				fileOutputStream.write(buff);
			}
			raf.seek(raf.length());
			if (raf.length() > 0) {
				content = "\n" + content;
			}
			raf.write(content.getBytes());
			// 追加文件插入点之后的内容
			while ((hasRead = fileInputStream.read(buff)) > 0) {
				raf.write(buff, 0, hasRead);
			}
			raf.close();
			fileInputStream.close();
			fileOutputStream.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 描述：是否有存在内存卡
	 * 
	 * @return
	 */
	public static boolean isSdcardExisting() {
		final String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 保存图片到指定的目录
	 * 
	 * @param bit
	 * @param fileName
	 *            文件名
	 * @return
	 */
	public static String saveBitToSD(Bitmap bit, String fileName) {
		if (bit == null || bit.isRecycled())
			return "";

		File file = new File(AntConstant.IMAGE_DIR);
		File dirFile = new File(file.getAbsolutePath());

		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		File pathFile = new File(dirFile, fileName);

		if (!pathFile.exists()) { // 存在文件先删除
			//deleteFile(pathFile);
			try {
				pathFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		ImageUtil.Bitmap2File(bit, pathFile.getAbsolutePath());

		return pathFile.getAbsolutePath();
	}

	/**
	 * 递归删除 文件/文件夹
	 * 
	 * @param file
	 */
	public static void deleteFile(File file) {
		// XLog.log("delete file path=" + file.getAbsolutePath());

		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();

				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}

			// file.delete(); // 删除目录
		} else {
			// XLog.log("delete file no exists " + file.getAbsolutePath());
		}
	}

	/**
	 * bitmap转字符串
	 * 
	 * @param bitmap
	 * @return
	 */
	public static String bitmaptoString(Bitmap bitmap) {
		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

	public static byte[] bitmaptoByte(Bitmap bitmap) {
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		// string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return bytes;
	}

	public static Bitmap convertToBitmap(String path) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		// 设置为ture只获取图片大小
		opts.inJustDecodeBounds = true;
		opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
		// 返回为空
		BitmapFactory.decodeFile(path, opts);
		int width = opts.outWidth;
		int height = opts.outHeight;
		float scaleWidth = 0.f, scaleHeight = 0.f;
		// if (width > w || height > h) {
		// // 缩放
		// scaleWidth = ((float) width) / w;
		// scaleHeight = ((float) height) / h;
		// }
		opts.inJustDecodeBounds = false;
		float scale = Math.max(scaleWidth, scaleHeight);
		opts.inSampleSize = (int) scale;
		WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
		return Bitmap.createScaledBitmap(weak.get(), width, height, true);
	}

	public static boolean fileIsExists() {
		try {
			File f = new File(AntConstant.IMAGE_DIR + SharedUtil.getString(AntConstant.SP_MOBILE, "123456789")+".jpg");
			if (!f.exists()) {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}
